<template>
	<view class="search-contanier">
		<view class="search flex-sb">
			<u-search placeholder="请输入关键字..." :focus="true"
				:actionStyle="{padding:'10rpx',color:'#fff',borderRadius:'50px',background:'linear-gradient(to right,#01ab36,#00e500)'}"
				height="30" :clearabled="true" v-model="searchValue" @custom="onSearch()" @search="onSearch()">
			</u-search>
		</view>
		<view class="search-history" v-if="historySearch.length">
			<view class="history-head flex-sb">
				<text class="text">搜索历史</text>
				<unt-icon name="icon-shanchu" size="20" @click="clearSearch()"></unt-icon>
			</view>
			<view class="history-content flex flex-start flex-wrap">
				<view class="mode" v-for="(val, index) in historySearch" :key="index">
					<text @click="handleQuick(val)">{{val}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const HISTORY_SEARCH = 'historySearch'
	export default {
		data() {
			return {
				historySearch: [],
				searchValue: '',
			}
		},
		mounted() {
			this.historySearch = this.getHistorySearch();
		},
		methods: {
			getHistorySearch() {
			    return uni.getStorageSync(HISTORY_SEARCH) || []
			},
			onSearch() {
				const { searchValue } = this
				if (searchValue) {
					// 记录历史搜索
					this.$unts.navTo('pages_moon/goods/list/list', { search: searchValue });
					this.setHistory(searchValue);
				}
			},
			setHistory(searchValue) {
				const data = this.getHistorySearch()
				const index = data.indexOf(searchValue)
				index > -1 && data.splice(index, 1)
				data.unshift(searchValue)
				this.historySearch = data
				this.onUpdateStorage()
			},
			onUpdateStorage(data) {
			    uni.setStorageSync(HISTORY_SEARCH, this.historySearch)
			},
			handleQuick(value) {
			    this.$unts.navTo('pages_moon/goods/list/list', { search: value})
			},
			clearSearch() {
			    this.historySearch = [];
			    this.onUpdateStorage()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.search-contanier {
		position: relative;
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.search {
			width: 100%;
			padding: 20rpx;
		}

		.search-history {
			width: 100%;
			padding: 20rpx;
			margin-top: 20rpx;

			.history-head {
				.text {
					font-size: 28rpx;
					font-weight: bold;
				}
			}

			.history-content {
				margin-top: 20rpx;

				.mode {
					margin: 0rpx 20rpx 20rpx 0rpx;
					font-size: 28rpx;
					padding: 10rpx 20rpx;
					border-radius: 100rpx;
					background-color: #f0f0f4;
				}
			}
		}
	}
</style>
